package pci.recommend

import dispatch._
import Http._
import dispatch.json._
//import Js._
import JsHttp._

import java.security.MessageDigest


/**
 * Delicious access function and extractor for json
 *
 */

object Delicious {
  val feeds = :/("feeds.delicious.com")
  val format = /("v2") / ("json")
  val popular = format / ("popular")

  val url = 'u ? str
  val tag = 't ? list
  val disp = 'd ? str
  val dt = 'dt ? str
  val user = 'a ? str
  val note = 'n ? str

  def getPopular(tag: String) = if (tag != null) feeds <& (popular / tag) else feeds <& popular
  def getUrl(u: String) = feeds <& format / "url" / md5SumString(u)
  def getUser(u: String) = feeds <& format / u

  /*  md5 hash for a array of Byte.  */
  def md5SumString(bytes: Array[Byte]): String = {
    val md5 = MessageDigest.getInstance("MD5")
    md5.reset()
    md5.update(bytes)
    md5.digest().map(0xFF & _).map {"%02x".format(_)}.foldLeft("") {_ + _} // mkString("") === foldLeft(""){_ + _}
  }
  def md5SumString(input: String): String = md5SumString(input.getBytes)
}

trait Extract extends Request with Js{
  def results = this ># {list}
  def urls = this ># {list ! Delicious.url}
  def tags = this ># {list ! Delicious.tag}
  def disps = this ># {list ! Delicious.disp}
  def dts = this ># {list ! Delicious.dt}
  def users = this ># {list ! Delicious.user}
  def notes = this ># {list ! Delicious.note}
}

case class Popular(tag: String) extends Request(Delicious.getPopular(tag)) with Js with Extract{}
case class Url(url: String) extends Request(Delicious.getUrl(url)) with Extract{}
case class User(name: String) extends Request(Delicious.getUser(name)) with Extract{}